<template>
  <div class="back-stage">
    <nav-bar />
    <h1>后台</h1>
    <div v-if="show">
      <h3>重新认证</h3>
      <!-- <el-input v-model="redirectUrl" placeholder="重定向网站" size="normal" clearable></el-input> -->
      <el-button type="primary" size="default" @click="openRegister"
        >打开认证页面</el-button
      >
      <el-input
        v-model="gitPath"
        placeholder="路径名（eg：/ or /doc）"
        size="normal"
        width="10"
        clearable
      ></el-input>
      <el-button type="primary" size="default" @click="getFiles"
        >读取目录</el-button
      >
      <br />
      <el-button type="primary" size="default" @click="openToken"
        >查看Token</el-button
      >
      <el-input
        type="textarea"
        v-model="tokenStr"
        placeholder="先重新认证，全选复制"
        size="normal"
        :rows="12"
        clearable
      ></el-input>
      <el-button type="primary" size="default" @click="updateToken"
        >更新远程Token</el-button
      >
      <br>
      <el-button type="primary" size="default" @click="reGetToken">刷新Token</el-button>
    </div>
    <div v-else>无权限，仅管理员！</div>
  </div>
</template>

<script>
import vConsole from "../common/vconsole";
import NavBar from "../components/NavBar.vue";
import { git } from "../config/info"

export default {
  name: "back-stage",
  components: {
    NavBar,
  },
  data() {
    return {
      show: false,
      data: git,
      redirectUrl: "",

      gitUpPath: "",
      gitPath: "",
      fileList: [],
      newFile: new FormData(),
      picThList: [],
      picList: [],
      tokenStr: "",
    };
  },
  methods: {
    reGetToken() {
      let tmp = ''
      if(this.tokenStr) {
        tmp = JSON.parse(this.tokenStr)['refresh_token']
      }
      this.$api.postInfo.reGetToken({refresh_token: tmp}).then(res => {
        let date = this.$moment(new Date(Number(new Date())+24*3600*1000)).format("YYYY-MM-DD HH:mm:ss")
        this.tokenStr=JSON.stringify(res)
        console.log(res, this.tokenStr, '----');
        this.updateToken()
        this.$message.success("刷新Token成功，有效期至", date)
      }).catch(err=>{})
    },
    openToken() {
      window.open(
        `https://gitee.com/${git.owner}/${git.repo}/blob/${git.branch}/token.txt`
        // "https://gitee.com/dusw/file-database-1/raw/master/token.txt"
      );
    },
    openRegister() {
      this.$api.getInfo.getCode({
        redirect_uri: encodeURIComponent(this.redirectUrl),
      });
    },
    updateToken() {
      const data = {
        ...this.data,
        path: "",
        access_token: JSON.parse(this.tokenStr)["access_token"],
      };
      this.$api.getInfo.getAllFile(data).then((res) => {
        let tmp = res.filter((nav) => nav.name.indexOf("token.txt") != -1)[0];
        console.log(tmp, "//");
        const query = {
          ...data,
          path: "token.txt",
          content: window.btoa(this.tokenStr),
          sha: tmp.sha,
          message: `更新token.txt ${this.$moment(new Date()).format(
            "YYYY-MM-DD HH:mm:ss"
          )}`,
        };
        this.$api.postInfo
          .updateFile(query)
          .then((res) => {})
          .catch((err) => {
            console.log(err);
            this.$message.success("更新成功！");
          });
      });
    },
    getBranch() {
      let data = this.data;
      this.$api.getInfo
        .getAllBranch(data)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {});
    },
    async uploadFile(resData, upDirPath, upTime) {
      let data = {
        ...this.data,
        content: resData,
        path: upDirPath,
        message: `上传${upDirPath}>${upTime}`,
      };
      await this.$api.postInfo
        .uploadNewfile(data)
        .then((res) => {
          console.log(res);
        })
        .catch((err) => {});
    },
    getFile(file, fileList) {
      console.log(file.raw);
      let nowDate = this.$moment(new Date()).format("YYYYMMDD");
      let upDir = `杂/${nowDate}/${file.raw.name}`;
      let upDir1 = `杂-th/${nowDate}/${file.raw.name}`;
      this.$utils.dealPic.getBase64(file.raw).then((res) => {
        let upTime = this.$moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
        let resData = res.split(";base64,")[1];
        let canv = this.$refs.canvas;
        let ctx = canv.getContext("2d");
        let img = new Image();
        img.src = res;
        img.onload = async () => {
          console.log(img, img.height, img.width, "+++");
          let point = 0;
          if (img.height > img.width) {
            point = Number(
              (
                Number(Math.floor(img.height / 2)) -
                Number(Math.floor(img.width / 2))
              ).toFixed(0)
            );
            ctx.drawImage(img, 0, point, img.width, img.width, 0, 0, 100, 100);
          } else if (img.height < img.width) {
            point = Number(
              (
                Number(Math.floor(img.width / 2)) -
                Number(Math.floor(img.height / 2))
              ).toFixed(0)
            );
            ctx.drawImage(
              img,
              point,
              0,
              img.height,
              img.height,
              0,
              0,
              100,
              100
            );
          }
          let dataUrl = canv.toDataURL("image/jpeg", 0.3);
          let resData1 = dataUrl.split(";base64,")[1];
          await this.uploadFile(resData1, upDir1, upTime);
          await this.uploadFile(resData, upDir, upTime);
        };
      });
    },
    getFiles() {
      const data = {
        ...this.data,
        path: this.gitPath,
      };
      this.$api.getInfo.getAllFile(data).then((res) => {
        console.log(this.gitPath, "下的所有文件", res);
      });
    },
    initPic() {
      this.$api.getInfo
        .getAllFile({
          ...this.data,
          path: "/demo-th",
        })
        .then((res) => {
          this.picThList = res;
        });

      this.$api.getInfo
        .getAllFile({
          ...this.data,
          path: "/demo",
        })
        .then((res) => {
          this.picList = res;
        });
    },
  },
  created() {
    this.redirectUrl = `https://${git.owner}.gitee.io/${git.project}/#/back-stage`
    if (this.$route.query && this.$route.query.admin == 1) {
      this.show = true;
    }
    let userInfo = JSON.parse(localStorage.getItem("userInfo"));
    this.tokenStr = JSON.stringify(userInfo);
    if (userInfo) {
      this.data["access_token"] = userInfo["access_token"];
    }
    let url = window.location.href;
    console.log(url);
    if (url.indexOf("?code=") != -1) {
      let data = {
        code: url.match(/code=(\w+)#\//)[1],
        redirect_uri: encodeURIComponent(this.redirectUrl),
      };
      this.$api.postInfo
        .registerWeb(data)
        .then((res) => {
          this.$message.success("新的Token设置成功！")
        })
        .catch((err) => {});
    }
  },
};
</script>

<style lang="scss" scoped>
.back-stage {
  ::v-deep.el-upload-list--picture .el-upload-list__item-thumbnail {
    object-fit: cover;
  }
}
</style>